<template>
  <div>
    <TableSearch
      ref="tableSearch"
      :search-path="searchPath"
      :columns="columns"
      :tableData="tableData"
      :tableBtns="tableBtns"
      :form="form"
      :formItemsInline="formItemsInline"
      :span-method="objectSpanMethod"
      @handleTableData="handleTableData"
      @reset="reset"
    >
      <template slot="address">
        <el-form-item>
          <HycAddressCascader ref="area" v-model="area" />
        </el-form-item>
      </template>
      <template slot="date">
        <el-form-item>
          <SearchDatePicker
            :start.sync="form.startTime"
            :end.sync="form.endTime"
          />
        </el-form-item>
      </template>
      <el-table-column label="所属电站" slot="stationName">
        <template #default="{ row }">
          <router-link
            :to="{
              name: 'StationDetail',
              params: { id: row.stationId },
              query: { type: 'ZTSocket' },
            }"
            >{{ row.stationName }}</router-link
          >
        </template>
      </el-table-column>
    </TableSearch>
    <EditDeviceThreshold
      @refreshTable="refreshTable"
      :visible.sync="editDeviceThresholdVisible"
      :option-attr="optionAttr"
    />
    <ViewDevice
      @refreshTable="refreshTable"
      :visible.sync="viewDeviceVisible"
      :type="viewDeviceType"
      :option-attr="optionAttr"
    />
    <BatchUpload
      v-if="batchUploadVisible"
      :visible.sync="batchUploadVisible"
      @refreshTable="refreshTable"
      :dialog-type="dialogType"
    ></BatchUpload>
    <PortsListForCentralSocket
      :visible.sync="viewPortsListVisible"
      :portsList="portsList"
    >
    </PortsListForCentralSocket>

    <TimeSelectionDialog
      v-if="timeSelectionModal"
      :portsList="portsList"
      :visible.sync="timeSelectionModal"
      @refresh="refreshTable"
    />

    <CommandSend ref="commandSend" />
  </div>
</template>
<script>
import TableSearch from '@/components/TableSearch'
import SearchDatePicker from '@/components/SearchDatePicker'
import HycAddressCascader from '@/components/hycAddressCascader'
import EditDeviceThreshold from './EditDeviceThreshold'
import ViewDevice from './ViewDevice'
import BatchUpload from './BatchUpload'
import PortsListForCentralSocket from './PortsListForCentralSocket'
import TimeSelectionDialog from '@/components/timeSelectionDialog'
import CommandSend from './CommandSend.vue'
import {
  deviceList,
  selfCheck,
  resetDevice,
  deviceVersionUp,
  deviceToExcel,
  resetCreateTime,
} from '@/api/device'
import { typeMap } from '@/utils/format'
import formatter from '@/utils/format'
export default {
  name: 'GatewayTable',
  components: {
    TableSearch,
    SearchDatePicker,
    HycAddressCascader,
    EditDeviceThreshold,
    ViewDevice,
    BatchUpload,
    PortsListForCentralSocket,
    TimeSelectionDialog,
    CommandSend,
  },
  data() {
    return {
      form: {
        city: null,
        district: null,
        province: null,
        deviceStatus: 'ALL',
      },
      tableData: {},
      area: {},
      optionAttr: {},
      portsList: {},
      searchPath: '/web/device-management/device-management/查询',
      batchUploadVisible: false,
      editDeviceThresholdVisible: false,
      viewDeviceVisible: false,
      viewDeviceType: '',
      viewPortsListVisible: false,
      timeSelectionModal: false,
      tableBtns: [
        {
          label: 'Excel批量注销',
          click: () => this.handleBatchUpload('ADMIN_LOGOUT'),
          icon: 'el-icon-delete',
          type: 'warning',
          resourceId: '/web/device-management/device-management/Excel批量注销',
        },
        {
          label: '(批量注销模板下载)',
          isDownload: true,
          href: require('../../../assets/batchTemplate/批量注销设备模板.xlsx'),
          fileName: '批量注销设备模板',
          resourceId:
            '/web/device-management/device-management/批量注销模板下载',
        },
        {
          label: '导出',
          isExport: true,
          startDownload: (callback) => {
            let params = Object.assign({}, this.form, this.area)
            params.deviceStatus === 'ALL' && delete params.deviceStatus
            deviceToExcel({
              ...params,
              currentPage: 1,
              deviceType: this.$attrs.type,
              pageSize: 10,
            })
              .then((res) => {
                callback(res)
              })
              .catch((err) => {
                console.log(err)
                callback(0)
              })
          },
          resourceId: '/web/device-management/device-management/导出',
        },
      ],
      formItemsInline: [
        {
          type: 'text',
          value: 'deviceId',
          placeholder: '请输入设备号',
          clearable: true,
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          type: 'text',
          value: 'stationName',
          placeholder: '请输入所属电站',
          clearable: true,
          resourceId: '/web/device-management/device-management/所属电站',
        },
        {
          type: 'text',
          value: 'mchName',
          placeholder: '请输入所属运营商',
          clearable: true,
          resourceId: '/web/device-management/device-management/所属运营商',
        },
        {
          type: 'text',
          value: 'versionNum',
          placeholder: '请输入版本号',
          clearable: true,
          ifRender: () => {
            return (
              this.$attrs.type === 'GATEWAY' ||
              this.$attrs.type === 'CENTRAL_SOCKET'
            )
          },
          resourceId: '/web/device-management/device-management/设备版本号',
        },
        {
          slot: 'address',
        },
        {
          slot: 'date',
        },
        {
          type: 'text',
          value: 'coupletCard',
          placeholder: '请输入物联卡号',
          clearable: true,
          ifRender: () => {
            return (
              this.$attrs.type === 'GATEWAY' ||
              this.$attrs.type === 'CENTRAL_SOCKET'
            )
          },
        },
        {
          type: 'select',
          value: 'gatewayType',
          placeholder: '网关类型',
          clearable: true,
          options: typeMap.selectOptions(
            ['ADMIN', 'SELF_OPERATION_ADMIN', 'NORMAL_USER'],
            'gatewayType'
          ),
          ifRender: () => {
            return (
              this.$attrs.type === 'GATEWAY' ||
              this.$attrs.type === 'CENTRAL_SOCKET'
            )
          },
          resourceId: '/web/device-management/device-management/设备类型',
        },
        {
          type: 'select',
          value: 'deviceStatus',
          placeholder: '设备状态',
          clearable: true,
          options:
            this.$attrs.type === 'GATEWAY' ||
            this.$attrs.type === 'CENTRAL_SOCKET'
              ? typeMap.selectOptions(
                  ['BREAK_DOWN', 'CHARGING', 'IDLE'],
                  'deviceStatus'
                )
              : typeMap.selectOptions(['ONLINE'], 'deviceStatus'),
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          type: 'select',
          value: 'socketNum',
          placeholder: '端口号',
          clearable: true,
          options: [
            { label: 1, value: 1 },
            { label: 2, value: 2 },
          ],
          resourceId: '/web/device-management/device-management/设备号',
        },
      ],
      columns: [
        {
          label: '设备号',
          prop: 'deviceId',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '设备端口号',
          prop: 'socketOrderNumber',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '设备版本号',
          prop: 'versionNum',
          resourceId: '/web/device-management/device-management/设备号',
        },

        {
          label: '注册状态',
          prop: 'activeDate',
          resourceId: '/web/device-management/device-management/设备号',
          formatter: (row) => {
            return row.activeDate ? '已注册' : '未注册'
          },
        },
        {
          slot: 'stationName',
          resourceId: '/web/device-management/device-management/所属电站',
        },
        {
          label: '所属位置',
          prop: 'stationAddress',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '所属运营商',
          prop: 'mchName',
          resourceId: '/web/device-management/device-management/所属运营商',
        },
        {
          label: '添加时间',
          prop: 'activeDate',
          resourceId: '/web/device-management/device-management/添加时间',
          formatter,
        },
        {
          label: '设备状态',
          prop: 'online',
          resourceId: '/web/device-management/device-management/状态',
          formatter: (row) => {
            return row.online ? '在线' : '失联'
          },
        },
        {
          label: '信号强度',
          prop: 'grpsSignal',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '设备电压',
          prop: 'voltage',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '插口状态',
          prop: 'socketsStatusValue',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '室内温度',
          prop: 'currentTemperature',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '电表数值',
          prop: 'ammeterNumber',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '通道电量（1分钟内）',
          prop: 'socketEnergy',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '通道线缆温度',
          prop: 'socketTemperature',
          resourceId: '/web/device-management/device-management/设备号',
        },
        {
          label: '操作',
          resourceId: '/web/device-management/device-management/操作',
          buttons: [
            {
              label: '升级',
              resourceId: '/web/device-management/device-management/升级',
              disabled: (row) => {
                return !row.online
              },
              click: this.handleUpgrade,
            },
            {
              label: '复位',
              resourceId: '/web/device-management/device-management/复位',
              click: this.handleResetDevice,
            },

            {
              label: '修改添加日期',
              ifRender: () => {
                return (
                  this.$attrs.type === 'GATEWAY' ||
                  this.$attrs.type === 'SOCKET' ||
                  this.$attrs.type === 'SWIPCARD_DEVICE' ||
                  this.$attrs.type === 'NB_DEVICE'
                )
              },
              resourceId:
                '/web/device-management/device-management/修改添加日期',
              click: (row) => {
                this.portsList = row
                this.alertAddTime()
              },
            },
            {
              label: '恢复日期',
              resourceId: '/web/device-management/device-management/恢复日期',
              click: (row) => {
                this.portsList = row
                this.recoverAddTime(row)
              },
            },
            {
              label: '端口详情',
              resourceId: '/web/device-management/device-management/端口详情',
              ifRender: () => {
                return this.$attrs.type === 'CENTRAL_SOCKET'
              },
              click: (row) => {
                this.viewPortsListVisible = true
                this.portsList = row
              },
            },
            {
              label: '查看',
              resourceId: '/web/device-management/device-management/查看',
              click: (row) => {
                this.viewDeviceType = this.$attrs.type
                this.viewDeviceVisible = true
                this.optionAttr = row
              },
            },
            {
              label: '生涯',
              resourceId: '/web/device-management/device-management/生涯',
              ifRender: () => {
                return (
                  this.$attrs.type === 'GATEWAY' ||
                  this.$attrs.type === 'CENTRAL_SOCKET'
                )
              },
              click: (row) => {
                this.$router.push({
                  path: '/device/deviceLog',
                  query: { deviceId: row.deviceId },
                })
              },
            },
            {
              label: '阈值配置',
              resourceId: '/web/device-management/device-management/阈值配置',
              ifRender: () => {
                return (
                  this.$attrs.type !== 'GATEWAY' &&
                  this.$attrs.type !== 'CENTRAL_SOCKET'
                )
              },
              click: (row) => {
                this.editDeviceThresholdVisible = true
                this.optionAttr = row
              },
            },
            {
              label: '自检',
              resourceId: '/web/device-management/device-management/自检',
              ifRender: () => {
                return (
                  this.$attrs.type !== 'GATEWAY' &&
                  this.$attrs.type !== 'CENTRAL_SOCKET'
                )
              },
              disabled: (row) => {
                return this.userId !== row.ownUserId
              },
              click: (row) => {
                const loading = this.$loading({
                  lock: true,
                  text: '设备自检中……',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.8)',
                })
                selfCheck({ socketId: row.socketId }).then(
                  (res) => {
                    loading.close()
                    this.$message({
                      type: 'success',
                      showClose: true,
                      message: res.breakDownReason || '自检成功',
                    })
                    this.refreshTable()
                  },
                  () => {
                    loading.close()
                  }
                )
              },
            },
            {
              label: '指令下发',
              click: (row) => {
                this.$refs.commandSend.handleOpen(row)
              },
            },
          ],
        },
      ],
    }
  },
  computed: {
    resourceSet() {
      return this.$store.getters.resourceSet
    },
    userId() {
      return this.$store.getters.userId
    },
  },
  methods: {
    //修改日期
    alertAddTime() {
      this.timeSelectionModal = true
    },

    //恢复添加日期
    recoverAddTime(row) {
      this.$confirm(`确认恢复修改前的日期？`, '恢复日期', {
        center: true,
        customClass: 'tip-dialog__wrapper',
      })
        .then(() => {
          resetCreateTime({
            deviceId: row.deviceId,
          }).then(() => {
            this.$message({
              message: '恢复成功',
              type: 'success',
            })
            this.refreshTable()
          })
        })
        .catch((err) => console.log(err))
    },

    reset() {
      this.form = {
        deviceStatus: 'ALL',
      }
      this.area = {}
    },
    handleBatchUpload(type) {
      this.batchUploadVisible = true
      this.dialogType = type
    },
    objectSpanMethod({ row, column }) {
      if (
        this.$attrs.type === 'GATEWAY' ||
        this.$attrs.type === 'CENTRAL_SOCKET' ||
        this.$attrs.type === 'ZT_SOCKET'
      ) {
        return
      }
      if (
        (column.label !== '状态' &&
          column.label !== '操作' &&
          column.label !== '端口号') ||
        (column.label === '操作' &&
          !this.resourceSet.includes(
            '/web/device-management/device-management/自检'
          ))
      ) {
        return {
          rowspan: row.socketLength,
          colspan: 1,
        }
      }
    },
    handleSocket(arr) {
      let list = []
      arr.forEach((item) => {
        let sockets = item.sockets || []
        sockets.forEach((socket, index) => {
          list.push({
            socketId: socket.socketId,
            socketStatus: socket.socketStatus,
            socketLength: index === 0 ? sockets.length : 0,
            ...item,
          })
        })
      })
      return list
    },
    handleResetDevice(row) {
      this.$confirm(`您确定要复位设备号为${row.deviceId}的设备吗？`, '提示', {
        center: true,
        customClass: 'tip-dialog__wrapper',
      })
        .then(() => {
          resetDevice({
            deviceId: row.deviceId,
          }).then(() => {
            this.$message({
              message: '复位成功',
              type: 'success',
            })
            this.refreshTable()
          })
        })
        .catch((err) => console.log(err))
    },
    handleUpgrade(row) {
      const loading = this.$loading({
        lock: true,
        text: '操作进行中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
      })
      deviceVersionUp({ batchTimeout: 30, deviceId: row.deviceId }).then(
        () => {
          loading.close()
          this.$message({
            type: 'success',
            message: '指令下发成功，跳转升级结果页面',
          })
          this.$router.push('/device/upgrade')
        },
        () => {
          loading.close()
        }
      )
    },
    handleTableData(params) {
      if (params.deviceStatus === 'ALL') {
        delete params.deviceStatus
      }
      params = { ...params, ...this.area, deviceType: this.$attrs.type }
      // if (this.$attrs.type === 'CENTRAL_SOCKET') {
      //   // 如果是集中式设备查询更换代理商名称字段
      //   if (params['mchName']) {
      //     params['centralMchName'] = params['mchName']
      //     params['mchName'] = ''
      //   }
      // }
      deviceList(params).then((res) => {
        console.log(res)
        console.log(this.$attrs.type)
        this.tableData = {
          list:
            this.$attrs.type === 'GATEWAY' ||
            this.$attrs.type === 'CENTRAL_SOCKET' ||
            this.$attrs.type === 'ZT_SOCKET'
              ? res.list
              : this.handleSocket(res.list),
          totalCount: res.totalAmount,
        }
      })
    },
    refreshTable() {
      console.log(11111)
      this.$refs['tableSearch'].refreshTable()
    },
  },
}
</script>
